package com.cafe.action.web;

import java.util.List;

import javax.servlet.http.Cookie;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;

import com.cafe.model.Product;
import com.cafe.service.ProductService;
import com.malamute.core.action.BaseAction;
import com.malamute.core.exception.BusinessException;

/**
 * @Description 购物车Action控制
 * 
 */
public class ShopCartAction extends BaseAction {
	// 订购的，从json中获取过来
	private List<Product> products;
	private Product product;
	@Autowired
	private ProductService productService;
	private String ids;// product id字符串 用;分隔

	// 根据商品ID获取商品
	public String loadProductById() {
		if (product != null) {
			product = productService.getProductById(product.getId());
		}
		return "product";
	}

	public String loadProductsByIds() {
		String[] strArr = ids.split(";");
		DetachedCriteria criteria = DetachedCriteria.forClass(Product.class);
		Integer[] intArr = new Integer[strArr.length];
		for (int i = 0; i < strArr.length; i++) {
			String tmp = strArr[i];
			try {
				intArr[i] = Integer.parseInt(tmp);
			} catch (Exception e) {
				throw new BusinessException("string to int error");
			}
		}
		criteria.add(Restrictions.in("id", intArr));
		products = productService.listProductsByIds(criteria);
		return "products";
	}

	// 购物车详情
	public String loadCookie() {
		System.out.println(request.getCookies().length);
		Cookie[] cookies = request.getCookies();
		for (Cookie cookie : cookies) {
			System.out.println(cookie.getName());
			System.out.println(cookie.getValue());
		}
		return null;
	}

	public Product getProduct() {
		return product;
	}

	public void setProduct(Product product) {
		this.product = product;
	}

	public List<Product> getProducts() {
		return products;
	}

	public void setProducts(List<Product> products) {
		this.products = products;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

}
